do-while Loop in C

Posted on November 2, 2023 by Vishesh Namdev
Python C C++ Java
C Programming Language

do-while loop in C is similar to a while loop, but it guarantees that the code block is executed at least once, even if the condition is false from the beginning. The condition is checked after the code block is executed

Syntax of do-while Loop:
do {
// Code to be executed
} while (condition);
Structure of a do-while Loop:

The do-while loop is unique because it ensures that the body of the loop is executed at least once, regardless of the initial condition. Here's how it works:

1. Initial Execution: When the program reaches the do-while loop, it immediately executes the body of the loop before checking the condition. In contrast to other loops, where the condition is checked before entering the loop, the do-while loop's behavior is often referred to as "exit controlled" or "post-tested."

2. Repeating Execution: If the condition is true after the first execution of the body, the program returns to the beginning of the loop and repeats the body's execution. This process continues as long as the condition remains true.

3. Exit on False Condition: When the condition eventually becomes false, the program exits the loop and continues with the statements following the do-while loop.

Example of do-while Loop:

Here's a basic example of a example loop in C that prints numbers from 1 to 5:

#include <stdio.h>Copy Code
int main() {
   int count = 1;
  // Initialization
  do {
    printf("Iteration %d\n",count);// Code block
     count++; // Updation
  } while (count <= 5); // Condition check
  return 0;
    }
Explanantion of above example:

1. Initialization: Start by initializing a variable (`count` in this case).

2. Code Execution: Execute the code block (in this example, it prints "Iteration X") unconditionally.

3. Condition Check: After executing the code block, check the condition (`count <= 5`).

4. Repetition: If the condition is true, repeat the code block.
- In the example, the loop continues printing numbers from 1 to 5.
- After each iteration, increment the variable (`count++`) to move closer to the condition becoming false.

5. Loop Termination: The loop continues repeating until the condition becomes false. - In this example, it ends when `count` becomes greater than 5.